package com.daifeng.authserver.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.daifeng.authserver.feign.MemberFeign;
import com.daifeng.authserver.feign.SendCode;
import com.daifeng.authserver.util.HttpUtils;

import com.daifeng.common.constant.UserConstant;
import com.daifeng.common.vo.MemberResponseVO;
import com.daifeng.common.constant.AuthServerConstant;
import com.daifeng.common.exception.BizCodeEnum;
import com.daifeng.common.utils.R;
import com.daifeng.common.vo.socialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Controller
public class LoginController {

    @Resource
    SendCode sendCode;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Resource
    MemberFeign MemberFeign;

    /**
     * 微博登录成功的回调
     * @param code  换取Access Token的凭证
     * @return
     */
    @RequestMapping("/oath2/success")
    public String success(@RequestParam("code")String code, HttpSession session) throws Exception {
        // 1. 使用code换取Accesstoken，换取成功则继续  2，否则重定向至登录页
        // 设置请求参数
        Map<String,String>  map = new HashMap<>();
        map.put("client_id","1591099180");
        map.put("client_secret","6e1cbaaeef2a6d43dc3fd9716b9f7596");
        map.put("grant_type","authorization_code");
        map.put("code",code);
        map.put("redirect_uri","http://auth.gulimall.com/oath2/success");
        Map<String, String> errors = new HashMap<>();
        HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", null, null, map);
        if(response.getStatusLine().getStatusCode() == 200){
            String str = EntityUtils.toString(response.getEntity());
            socialUser user = JSON.parseObject(str, new TypeReference<socialUser>() {
            });
            //2. 调用member远程接口进行oauth登录，登录成功则转发至首页并携带返回用户信息，否则转发至登录页
            R r = MemberFeign.login(user);
            //  远程调用成功  获取返回信息 并返回给页面
            if(r.getCode() == 0){
                String jsonString = JSON.toJSONString(r.get("data"));
                MemberResponseVO memberResponseVo = JSON.parseObject(jsonString, new TypeReference<MemberResponseVO>() {
                });
                session.setAttribute("loginUser", memberResponseVo);
            }else {
                // 否则返回登录页
                errors.put("msg", "登录失败，请重试");
                session.setAttribute("errors", errors);
                return "redirect:http://auth.gulimall.com/login.html";
            }
       }
// else {
//            errors.put("msg", "获得第三方授权失败，请重试");
//            session.setAttribute("errors", errors);
//            return "redirect:http://auth.gulimall.com/login.html";
//        }

        return "redirect:http://gulimall.com/home";
    };


    @GetMapping("/sms/sendcode")
    @ResponseBody
     public R sendCode(String phone){

        // 生成验证码
        String code = UUID.randomUUID().toString().substring(0, 5);
        //  存入redis  验证码的key
        String prefixPhone =  AuthServerConstant.SMS_CODE_CACHE_PREFIX+phone;
        // 取出redis中的验证码
        String redisCode = redisTemplate.opsForValue().get(prefixPhone);

        if (!StringUtils.isEmpty(redisCode)){
            long l = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis() -l < 60000){
                //60秒内不能再发
                return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(),BizCodeEnum.SMS_CODE_EXCEPTION.getMsg());
            }
        }
        //  将验证码存入redis中  格式  验证码_当前系统时间
        redisTemplate.opsForValue().set(prefixPhone,code + "_" + System.currentTimeMillis(),10, TimeUnit.MINUTES);
        sendCode.sendSms(phone,code);
        return R.ok();
     }

}
